package com.example.musicplayer.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.musicplayer.R;
import com.example.musicplayer.bean.Song;
import com.example.musicplayer.utils.Data;
import com.example.musicplayer.utils.GetAllActivity;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PlayerActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private List<Song> list;
    private List<Song> tempList;
    private int position;
    private TextView txtv_head;
    private SeekBar seekBar;
    private TextView txtv_player_timestart;
    private TextView txtv_player_timeend;
    private ImageView imgv_player_main;
    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。
    private boolean isMediaPlayerPrepared;//防止准备时依旧访问MediaPlayer
    private int currentPosition;//当前音乐播放的进度
    private Timer timer;
    private SimpleDateFormat formatter;
    private Handler handler;
    private Boolean isWEBAlbum = false;
    private Boolean isPlaying = false;
    private ImageView iv_player_playstart;
    private ImageView iv_player_playbefore;
    private ImageView iv_player_playafter;
    //播放状态控制
    private ImageView iv_player_playmod;
    private int playerMod = 1;//1:列表循环 2：单曲循环 3：列表随机
    //爱心处理
    private ImageView iv_player_love;
    private Boolean isLoved = false;
    private long rotationStartTime;
    private Button btn1;
    //通知栏
    public static NotificationManager manager;
    RemoteViews remoteViews;
    Notification notification;
    int state = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        formatter = new SimpleDateFormat("mm:ss");
        //注册开始结束时间条组件
        txtv_player_timestart = findViewById(R.id.txtv_player_timestart);
        txtv_player_timeend = findViewById(R.id.txtv_player_timeend);
        btn1=findViewById(R.id.button2);
        btn1.setOnClickListener(new btu1());
        GetAllActivity.getInstance().addActivity(this);
        //确认是否为网络歌单
        isWEBAlbum = getIntent().getBooleanExtra("isWEBAlbum",false);
        System.out.println(isWEBAlbum);
        //初始化歌单
        list = (List<Song>) getIntent().getSerializableExtra("musicData");
        position = getIntent().getIntExtra("position",0);
        //初始化首页图
        imgv_player_main = findViewById(R.id.imgv_player_main);
        initPlayerMainPic();

        //初始化mediaPlayer
        initMediaPlayer();

        //初始化顶部工具栏
        txtv_head = findViewById(R.id.txtv_player_head);
        txtv_head.setText(list.get(position).song);
        ImageView btn_player_back = findViewById(R.id.btn_player_back);
        btn_player_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlayerActivity.this.finish();
            }
        });


        //播放事件
        iv_player_playstart= findViewById(R.id.iv_player_playstart);
        iv_player_playstart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放中按
                if(isPlaying){
                    mediaPlayer.pause();
                    isPlaying = false;
                    iv_player_playstart.setImageDrawable(getDrawable(R.drawable.musicplay));

                    float rotationTime =System.currentTimeMillis()-rotationStartTime;
                    imgv_player_main.setPivotX(imgv_player_main.getWidth()/2);
                    imgv_player_main.setPivotY(imgv_player_main.getHeight()/2);
                    //360/20000=0.018 指main pic转速
                    imgv_player_main.setRotation(imgv_player_main.getRotation()+(rotationTime*(float) 0.018));
//                    System.out.println(rotationTime);
                    imgv_player_main.invalidate();
//                    System.out.println(imgv_player_main.getRotation());
                    imgv_player_main.clearAnimation();

                }else{
                    //停止中按
                    mediaPlayer.start();
                    rotateMainPic();
                    isPlaying = true;
                    iv_player_playstart.setImageDrawable(getDrawable(R.drawable.musicstop));
                }

            }
        });

        //上一首事件
        iv_player_playbefore = findViewById(R.id.iv_player_playbefore);
        iv_player_playbefore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(timer!=null){
                    timer.cancel();
                    timer = null;
                }
                if(mediaPlayer!=null){
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                    if(position==0){
                        position = list.size()-1;
                    }else{
                        position = position-1;
                    }
                    txtv_head.setText(list.get(position).song);
                     initPlayerMainPic();
                    initMediaPlayer();
            }
        });
        //下一首事件
        iv_player_playafter = findViewById(R.id.iv_player_playafter);
        iv_player_playafter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(timer!=null){
                    timer.cancel();
                    timer = null;
                }
                if(mediaPlayer!=null){
                    mediaPlayer.stop();
                    mediaPlayer.release();
                }
                    if(position+1==list.size()){
                        position = 0;
                    }else{
                        position = position+1;
                    }
                    txtv_head.setText(list.get(position).song);
                initPlayerMainPic();
                initMediaPlayer();
            }
        });
        //处理进度条
        seekBar = (SeekBar) findViewById(R.id.sb_player_main);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());
        //爱心处理
        iv_player_love = findViewById(R.id.iv_player_love);
        //处理初始爱心状态
        String url = getString(R.string.web_ip)+"/songs/isLoved";
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        final Data data = (Data)getApplication();
        try {
            json.put("song_id",list.get(position).id);
            json.put("user_id",data.getUserID());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON,json.toJSONString()); // new
        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data = response.body().string();
                if(data.equals("\"isLoved\"")){
                    isLoved = true;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            iv_player_love.setImageDrawable(getDrawable(R.drawable.player_love_color));
                        }
                    });
                }
            }
        });

        iv_player_love.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isLoved){
                    String url = getString(R.string.web_ip)+"/songs/myLove";
                    OkHttpClient okHttpClient = new OkHttpClient();
                    MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                    JSONObject json = new JSONObject();
                    final Data data = (Data)getApplication();
                    try {
                        json.put("song_id",list.get(position).id);
                        json.put("user_id",data.getUserID());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    RequestBody body = RequestBody.create(JSON,json.toJSONString()); // new
                    final Request request = new Request.Builder()
                            .url(url)
                            .post(body)
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {

                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            String data = response.body().string();
                            System.out.println(data);
                            isLoved = true;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    iv_player_love.setImageDrawable(getDrawable(R.drawable.player_love_color));
                                }
                            });
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(), "已收藏", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    });
                }else{
                    String url = getString(R.string.web_ip)+"/songs/deleteLove";
                    OkHttpClient okHttpClient = new OkHttpClient();
                    MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                    JSONObject json = new JSONObject();
                    final Data data = (Data)getApplication();
                    try {
                        json.put("song_id",list.get(position).id);
                        json.put("user_id",data.getUserID());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    RequestBody body = RequestBody.create(JSON,json.toJSONString()); // new
                    final Request request = new Request.Builder()
                            .url(url)
                            .post(body)
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {

                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            String data = response.body().string();
                            System.out.println(data);
                            isLoved = false;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    iv_player_love.setImageDrawable(getDrawable(R.drawable.player_love));
                                }
                            });
                            Looper.prepare();
                            Toast.makeText(getApplicationContext(), "已移除我喜欢歌单", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    });
                }

            }
        });
        if(!isWEBAlbum){
            iv_player_love.setVisibility(View.INVISIBLE);
        }



        //播放状态切换
        iv_player_playmod = findViewById(R.id.iv_player_playmod);
        tempList = new ArrayList<Song>();
        iv_player_playmod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(playerMod==1){
                    playerMod=2;
                    tempList.addAll(list);
                    Song now = list.get(position);
                    list.clear();
                    list.add(now);
                    position = 0;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            iv_player_playmod.setImageDrawable(getDrawable(R.drawable.player_repeat_one));
                        }
                    });
                }else if(playerMod==2){
                    playerMod=3;
                    list.clear();
                    list.addAll(tempList);
                    Collections.shuffle(list);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            iv_player_playmod.setImageDrawable(getDrawable(R.drawable.player_random));
                        }
                    });
                }else if(playerMod==3){
                    list.clear();
                    list.addAll(tempList);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            iv_player_playmod.setImageDrawable(getDrawable(R.drawable.player_repeat));
                        }
                    });
                }
            }
        });

    }

    //进度条处理
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }
        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }
        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
        timer = null;
        if(mediaPlayer!=null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if(manager != null ){
            manager.cancel(0);
        }

    }

    private void initMediaPlayer(){
        mediaPlayer = new MediaPlayer();
        try {
            if(isWEBAlbum){
                String source =getString(R.string.web_ip)+"/songs/player/"+list.get(position).id;
                System.out.println(source);
                mediaPlayer.setDataSource(source);
            }else{
                mediaPlayer.setDataSource(list.get(position).path);
            }

            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.seekTo(currentPosition);
                    seekBar.setMax(mediaPlayer.getDuration());
                    String endTime =formatter.format(mediaPlayer.getDuration());
                    txtv_player_timeend.setText(endTime);
                    rotateMainPic();
                    //监听播放时回调函数
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if(!isSeekBarChanging){
                                seekBar.setProgress(mediaPlayer.getCurrentPosition());
                                PlayerActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(mediaPlayer != null){
                                            if(mediaPlayer.isPlaying()){
                                                txtv_player_timestart.setText(formatter.format(mediaPlayer.getCurrentPosition()));
                                            }
                                        }

                                    }
                                });
                            }
                        }
                    },0,50);
                    mp.start();
//                    createNotification();
                    isPlaying = true;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            iv_player_playstart.setImageDrawable(getDrawable(R.drawable.musicstop));
                        }
                    });
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createNotification(){
        NotificationManager notificationManager = (NotificationManager) getSystemService
                (NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        notification = new Notification();
        notification.tickerText = "title";
        notification.icon =R.drawable.find_daily;
        notification.when = System.currentTimeMillis();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        remoteViews = new RemoteViews(getPackageName(),
                R.layout.player_notify);
        remoteViews.setTextViewText(R.id.wt_title, list.get(position).song);
        remoteViews.setImageViewBitmap(R.id.icon1,finalBitmap);
        if(state == 0){
            remoteViews.setImageViewResource(R.id.wt_play,R.drawable.musicplay);
        }else {
            remoteViews.setImageViewResource(R.id.wt_play,R.drawable.musicstop);
        }

        Intent previous=new Intent("com.example.broadcasttest.PREVIOUS");
        PendingIntent pi_previous = PendingIntent.getBroadcast(PlayerActivity.this,0,
                previous,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.wt_previous,pi_previous);


        Intent play=new Intent("com.example.broadcasttest.PLAY");
        PendingIntent pi_play = PendingIntent.getBroadcast(PlayerActivity.this,0,
                play,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.wt_play,pi_play);

        Intent next=new Intent("com.example.broadcasttest.NEXT");
        PendingIntent pi_next = PendingIntent.getBroadcast(PlayerActivity.this,0,
                next,PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.wt_next,pi_next);

        notification.contentView = remoteViews;
        manager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        manager.notify(1,notification);
    }


    /**
     * 根据专辑ID获取专辑封面图
     * @param album_id 专辑ID
     * @return
     */
    private Bitmap getAlbumArt(long album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = this.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Long.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        Bitmap bm = null;
        if (album_art != null) {
            bm = BitmapFactory.decodeFile(album_art);
        } else {
            bm = BitmapFactory.decodeResource(getResources(), R.drawable.musicpic);
        }
        return bm;
    }
    Bitmap finalBitmap;
    private  void getImageFromNetByUrl(String src){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(src)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //得到从网上获取资源，转换成我们想要的类型
                byte[] Picture_bt = response.body().bytes();
                Bitmap bitmap = null;
                if (Picture_bt.length != 0) {
                    bitmap = BitmapFactory.decodeByteArray(Picture_bt, 0, Picture_bt.length);
                }
                finalBitmap = bitmap;
                PlayerActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), finalBitmap); //创建RoundedBitmapDrawable对象
                        roundedBitmapDrawable.setCornerRadius(5000); //设置圆角Radius（根据实际需求）
                        roundedBitmapDrawable.setAntiAlias(true); //设置抗锯齿
                        imgv_player_main.setImageDrawable(roundedBitmapDrawable);
                    }
                });
            }
        });
    }

    private void initPlayerMainPic(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                if(isWEBAlbum){
                    String url = getString(R.string.web_ip)+"/cover/"+list.get(position).id;
                    getImageFromNetByUrl(url);
                }else{
                    PlayerActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgv_player_main.setImageBitmap(getAlbumArt(list.get(position).albumId));
                            imgv_player_main.setPivotX(imgv_player_main.getWidth()/2);
                            imgv_player_main.setPivotY(imgv_player_main.getHeight()/2);
                            imgv_player_main.setRotation(0);
                            rotationStartTime = System.currentTimeMillis();
                        }
                    });
                }
            }
        });
        thread.start();
    }

    private void rotateMainPic(){
        Animation operatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        if (operatingAnim != null) {
            imgv_player_main.startAnimation(operatingAnim);
            rotationStartTime = System.currentTimeMillis();
            System.out.println("开始时间"+rotationStartTime);
        }

    }

    class btu1 implements View.OnClickListener {
        public void onClick(View v) {
        }
    }
}